package com.xiangshizhineng.tianzhangzhi.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiangshizhineng.tianzhangzhi.app.common.R;
import com.xiangshizhineng.tianzhangzhi.app.filter.AppToken;
import com.xiangshizhineng.tianzhangzhi.app.model.entity.MesReturn;
import com.xiangshizhineng.tianzhangzhi.app.model.entity.TzMes;
import com.xiangshizhineng.tianzhangzhi.app.model.response.*;
import com.xiangshizhineng.tianzhangzhi.app.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.xiangshizhineng.tianzhangzhi.app.utils.ConstantUtils.*;

@RestController
@RequestMapping("/mes")
@Slf4j
@Api(tags = "任务提醒(消息队列)")
public class MesController{

    //    private final Semaphore permit = new Semaphore(50, true);
    @Autowired
    MesService mesService;

    @Autowired
    TaskService taskService;

    @Autowired
    NoticeService noticeService;

    @Autowired
    EventService eventService;

    @Autowired
    UserService userService;

    @Autowired
    DistrictService districtService;

    @ApiOperation(value = "消息刷新", notes = "消息刷新")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/selectMes")
    @AppToken
    public R<MesReturn> selectMes(HttpServletRequest request){
        Map<String, Object> params = new HashMap<>();
        String userId =request.getParameter("userId");
        MesReturn mesReturn = new MesReturn();
        UserResponse user = userService.getOne(new QueryWrapper<UserResponse>().select("xzqdm","tzjb").eq("id",userId));
        String xzqbh = user.getXzqdm();
        DistrictResponse districtResponse = districtService.getOne(new QueryWrapper<DistrictResponse>().select("level","id").eq("code",xzqbh));
        String level = districtResponse.getLevel();
        Long id = districtResponse.getId();
        List<DistrictResponse> disList = districtService.list(new QueryWrapper<DistrictResponse>().select("code").eq("pid",id));
        List<String> idsCodeList = new ArrayList<>();
        disList.stream().forEach(t->{
            idsCodeList.add(t.getCode());
        });
        //任务提醒
        //二级
        if(!TZJB_2.equals(level)&&!TZJB_1.equals(level)){
            //任务
            mesReturn.setTaskMes(taskService.allTasksByIdCountMes(new QueryWrapper<TaskResponse>().eq("t.xzqhdm",xzqbh)));
            //催办任务
            mesReturn.setCbTaskMes(taskService.allTasksByIdCountMes(new QueryWrapper<TaskResponse>().eq("t.cb","1").eq("t.xzqhdm",xzqbh).isNull("t.task_xcr")));
        }else{
            //任务
            mesReturn.setTaskMes(taskService.allTasksByIdCountMes(new QueryWrapper<TaskResponse>().in("t.xzqhdm",idsCodeList)));
            //催办任务
            mesReturn.setCbTaskMes(taskService.allTasksByIdCountMes(new QueryWrapper<TaskResponse>().eq("t.cb","1").isNull("t.task_xcr").in("t.xzqhdm",idsCodeList)));
        }
        //新事件提醒
        mesReturn.setEventMes(eventService.count(new QueryWrapper<EventResponse>().eq("handler",userId).eq("event_status_id","11")));

        //新公告提醒
        //判断公告是否在有有效期内
        int noticeNewMes = noticeService.count(new QueryWrapper<NoticeResponse>()
                .lambda()
                .le(NoticeResponse::getStartDate,new Date())
                .ge(NoticeResponse::getEndDate,new Date()));
        mesReturn.setNoticeMes(noticeNewMes);

        //催办事件提醒
        mesReturn.setCbEventMes(eventService.count(new QueryWrapper<EventResponse>().eq("cb","1").eq("handler",userId).eq("event_status_id","11")));
        return R.success(mesReturn);
    }

    @ApiOperation(value = "公告提醒清空", notes = "新消息提醒一个小时后清空公告提醒")
    @PostMapping("/noticeRefresh")
    @AppToken
    public R noticeRefresh(){
        UpdateWrapper<TzMes> updateWrapper = new UpdateWrapper<TzMes>();
        updateWrapper.set("state","1");
        updateWrapper.eq("type","3");
        boolean res = mesService.update(updateWrapper);
        if(res){
            return R.success("公告消息清空成功");
        }else{
            return R.fail("无公告消息可清空");
        }
    }
}
